const mqtt = require('mqtt');

const client = mqtt.connect(`mqtt://${'39.106.34.123'}:${1883}`, {
  username: '',
  password: '',
  clientId: 'test'
});

let messageCount = 0;
let startTime;

client.on('connect', () => {
  console.log('Connected to MQTT broker');
  client.subscribe('/topic/test1');
  startTime = Date.now(); // 记录开始时间
});

client.on('message', (topic, message) => {
  messageCount++;
  if (messageCount%1000==0) {
    const endTime = Date.now(); // 记录结束时间
    const elapsedTime = (endTime - startTime)/1000 ; // 计算消耗的时间（秒）
    console.log(`${messageCount} :${elapsedTime.toFixed(2)}`);
    messageCount = 0; // 重置计数器
    startTime = Date.now(); // 重置开始时间
  }
  // 可以在这里处理接收到的消息
//   console.log(`Received message: ${message.toString()}`);
});

client.on('error', (error) => {
  console.error('MQTT client error:', error);
});

client.on('close', () => {
  console.log('MQTT client disconnected');
});